import 'package:flutter/cupertino.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/poi_search.dart';
import 'package:t3_data_service/data_provider/live_location/t3_live_location_provider.dart';
import 'package:t3_data_service/foundation/foundation.dart';
import 'package:t3_foundation/t3_foundation.dart';
import '../../configs/address_select_config.dart';
import '../../configs/poi_search_base_config.dart';
import '../../data_report/address_log.dart';

class POISearchCellViewModel {
  final POIModel poi;
  final AddressSelectConfig config;
  POISearchCellViewModel(this.poi, this.config);

  Map<String, dynamic>? mapSelectedData;
  bool showDivider = true;
  bool showShareButton = false;

  T3POIStyle style = T3POIStyle.normal;
  BorderRadius? corner;

  int? selectedSubPOIIndex;
  int? shareSubPOIIndex;

  POISearchCellViewModel copy() {
    var vm = POISearchCellViewModel(poi, config);
    vm.mapSelectedData = mapSelectedData;
    vm.showDivider = showDivider;
    vm.showShareButton = showShareButton;
    vm.style = style;
    vm.corner = corner;
    vm.selectedSubPOIIndex = selectedSubPOIIndex;
    vm.shareSubPOIIndex = shareSubPOIIndex;
    return vm;
  }

  bool get isValid {
    if (mapSelectedData != null) {
      var model = AddressPoi.fromJson(mapSelectedData!);
      if (LatLng.isLatLngValid(model.location)) {
        return true;
      }
    } else {
      if (LatLng.isLatLngValid(poi.location)) {
        return true;
      }
    }
    return false;
  }

  LatLng get realLocation {
    if (mapSelectedData != null) {
      var model = AddressPoi.fromJson(mapSelectedData!);
      return model.location;
    } else {
      return poi.location;
    }
  }

  updateMapSelectedData(Map mapSelected) {
    var result = <String, dynamic>{};
    for (var key in mapSelected.keys) {
      if (key != null && key is String) {
        result[key] = mapSelected[key];
      }
    }
    mapSelectedData = result;
  }

  void markNeedNavPoint() {
    poi.runtimeParams.navPointCheck = true;
  }

  /// 对外提供的Model是POIModel的JSON
  Map<String, dynamic> jsonOutput(bool isInnerDataType) {
    var originSubs = poi.subPOIs;

    if (selectedSubPOIIndex == null) {
      poi.subPOIs = [];
    } else {
      var sub = poi.subPOIs.safeAccess(selectedSubPOIIndex);
      if (sub != null) {
        poi.subPOIs = [sub];
      }
    }
    if (isInnerDataType) {
      var jsonMap = poi.toJson();
      poi.subPOIs = originSubs;
      return jsonMap;
    }

    /// 图选数据
    if (mapSelectedData != null) {
      return mapSelectedData!;
    }
    var jsonMap = poi.toAddressPoi().toJson();
    poi.subPOIs = originSubs;
    return jsonMap;
  }
}

extension UIViewModel on POISearchCellViewModel {
  String get poiName => poi.name ?? '';
  String get poiAddress => poi.address ?? '';

  List<SubPOIModel> get subPOIs => poi.subPOIs ?? [];

  List<T3POITag> get topTags => poi.topTags ?? [];
  List<T3POITag> get bottomTags => poi.bottomTags ?? [];

  String get logoName {
    return "assets/images/poi_icon.webp";
  }

  String get distanceText {
    var distance = poi.distance;
    var validDistance = true;
    if (distance == 0) {
      /// 因为Model中distance默认值为0，所以为0需要二次校验
      validDistance = false;
      LatLng location;
      if (config.pointType == T3POIType.start) {
        /// 起点使用用户位置
        var liveLocation = T3LiveLocationProvider.instance.liveLocation;
        location =
            LatLng(liveLocation?.latitude ?? 0, liveLocation?.longitude ?? 0);
      } else {
        /// 终点使用起点位置
        var pinLocation = config.originCoor;
        location =
            LatLng(pinLocation?.latitude ?? 0, pinLocation?.longitude ?? 0);
      }

      if (LatLng.isLatLngValid(location)) {
        var cal = GeoUtils.getDistance(
            location.lat, location.lng, poi.location.lat, poi.location.lng);
        distance = cal.round();
        validDistance = true;
      } else {
        validDistance = false;
        logPOISearchDebug(
            'POI距离为0，且补偿失败：搜索类型：${config.pointType}，用户位置：${T3LiveLocationProvider.instance.liveLocation}, 搜索条件中起点位置：${config.originCoor}');
      }
    } else {
      validDistance = true;
    }
    /// 约定：如果距离无法按照约定标准计算出来，则不显示距离
    if (!validDistance) {
      return '';
    } else {
      /// 小于1000米，显示米
      if (distance < 1000) {
        return '${distance}m';
      } else {
        /// 大于1000米，显示公里
        var text = (distance / 1000.0).toStringAsFixed(1);
        return '${text}km';
      }
    }
  }

  String get multiInputDisplayName {
    var name = poi.name ?? '';
    var sname = poi.subPOIs.safeAccess(selectedSubPOIIndex)?.sname ?? '';
    var displayName = name + sname;
    return displayName;
  }

  String get multiInputCityName {
    var name = poi.city ?? '';
    if (name.endsWith('市')) {
      name = name.substring(0, name.length - 1);
    }
    return name;
  }
}